/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : booking.js                                 
*  Description  : 부킹게시판 리스트 
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-05-02  김효순    Created.  
*  2012-05-02  김효순    Complete.  
*******************************************************************************/

jQuery(function($){
	// 상단 타이틀
	function clsBookingTitle()
	{
		this._HTMLDom = null;
		
		this._init();
	}
	
	clsBookingTitle.prototype = {
		_init: function(){
			var $layer = $("div#container>section#main_content>div.golf_board article.depth2_tab");
			
			this._HTMLDom = {
				"$layer": $layer
				, "$tabs": $layer.find("li")
			}
			
			$layer.data("idx", null); // 인덱스로 관리
			
			this.display();
		}
		, setIdx: function(val){
			var $layer = this._HTMLDom["$layer"];
			
			if(val == $layer.data("idx")) return false;
			
			$layer.data("idx", val);
			
			this.display();
			return true;
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"], $tabs = this._HTMLDom["$tabs"];
			var idx = $layer.data("idx");
			
			// 현재 인덱싱된 타이틀만 on설정
			$tabs.find("img").each(function(n){
				var imgSrc = $(this).attr("src");
				var szImgName = imgSrc.replace(/(.*)\/(.*).gif/g, function(){
					return arguments[1] + "/" + arguments[2].replace("_on", "");
				});
				
				$(this).attr("src", szImgName + ((idx == n) ? "_on":"") + ".gif");
			});
		}
		// 탭 버튼
		, $getsBtnTab: function(){
			var $layer = this._HTMLDom["$layer"], $tabs = this._HTMLDom["$tabs"];
			
			return $tabs.find("a");
		}
	}
	
	// 검색타입
	function clsSearchType()
	{
		this._HTMLDom = null;
		this.idx = null;
		
		this._init();
	}
	
	clsSearchType.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content div.golf_board article.golf_board_search div.selectlayer");
			
			this._HTMLDom = {
				"$layer": $layer
			}
			this.idx = 0;
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, display: function(){
			var $layer = this.$getLayer();
			
			$layer.find("p:eq(0) a").html($layer.find("li a").eq(this.idx).html());
		}
		, setIdx: function(idx){
			this.idx = idx;
			this.display();
			this._HTMLDom["$layer"].find("ul").hide(300);
		}
		, $getSelect: function(){
			return this.$getLayer().find("ul");
		}
		, getValue: function(){
			return this.idx;
		}
		, setValue: function(val){
			this.idx = val;
			this.display();
		}
		, toggle: function(){
			var $layer = this.$getLayer();
			
			$layer.find("ul").toggle(300);
		}
		, show: function(){
			var $layer = this.$getLayer();
			
			$layer.find("ul").show(300);
		}
		, hide: function(){
			var $layer = this.$getLayer();
			
			$layer.find("ul").hide(300);
		}
	}
	
	// 검색어
	function clsSearchText()
	{
		this._HTMLDom = null;
		this._ERRMSG = {
			"_NOVALUE": "검색어를 입력해 주십시요."
		}
		this.errMsg = null;
		
		this._init();
	}
	
	clsSearchText.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content div.golf_board article.golf_board_search :text");
			this._HTMLDom = {
				"$layer": $layer
			}
		}
		, getValue: function(){
			return this._HTMLDom["$layer"].val();
		}
		, isValid: function(){
			this.errMsg = null;
			
			if(this.getValue() == ""){
				this.errMsg = this._ERRMSG["_NOVALUE"];
				return false;
			}
			
			return true;
		}
		, getError: function(){
			return this.errMsg;
		}
		, focus: function(){
			this._HTMLDom["$layer"].trigger("focus");
		}
		, $getObj: function(){
			return this._HTMLDom["$layer"];
		}
		, setValue: function(val){
			this._HTMLDom["$layer"].val(val);
		}
	}
	
	// 공지사항
	function clsNotice()
	{
		this._HTMLDom = null;
		this.infoData = null;
		
		this._init();
	}
	
	clsNotice.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content div.golf_board >dl.golf_board_note");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			this.setInfo({});
		}
		, setInfo: function(thisData){
			this.infoData = thisData;
			this.display();
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("dd").empty();
			if(this.infoData["공지키"]) $layer.find("dd").html(this.infoData["제목"]);
		}
	}
	
	// 부킹리스트
	function clsBookingList()
	{
		this._HTMLDom = null;
		this.listData = null;
		
		this._init();
	}
	
	clsBookingList.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content div.golf_board article.board_list");
			$layer.find("tr:first td:eq(2) img").error(function(){
				$(this).attr("src", _gf.getDefaultProfileImage());
			});
			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.find("tbody tr:first").clone(true)
				, "$noresult": $layer.prev("article.board_list_none")
			}
			
			this.setList([]);
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setList: function(thisData){
			this.listData = thisData;
			this.display();
		}
		, setWriter: function(boardKey, thisData){
			for(var i=0;i<this.listData.length;i++){
				if(boardKey == this.listData[i]["키"]) break;
			}
			
			if(i < this.listData.length){
				this.listData[i]["작성자"] = thisData;
				this.displayWriter(i);
			}
		}
		, display: function(){
			var $layer = this.$getLayer();
			var $element = this._HTMLDom["$element"];
			var $noresult = this._HTMLDom["$noresult"];
			var thisClass = this;
			
			if(this.listData.length){
				$layer.show();
				$noresult.hide();
				
				$layer.find("tbody").empty();
				for(var i=0;i<this.listData.length;i++){
					$layer.find("tbody").append($element.clone(true));
				}
				$layer.find("tbody tr").each(function(n){
					$(this).find("td:eq(0)").html(thisClass.listData[n]["번호"]);
					$(this).find("td:eq(1) a").html(thisClass.listData[n]["제목"]).click(function(){
						document.objControl.goViewPage(thisClass.listData[n]["키"]);
					});
					$(this).find("td:eq(1) span").html("(" + thisClass.listData[n]["댓글수"] + ")");
					$(this).find("td:eq(2) img").attr("src", _gf.getDefaultProfileImage());
					$(this).find("td:eq(2) span.nickname").html(thisClass.listData[n]["작성자"]["닉네임"]);
					$(this).find("td:eq(3)").html(thisClass.listData[n]["날짜"]);
					$(this).find("td:eq(4)").html(thisClass.listData[n]["조회수"]);
				});
			}else{
				$layer.hide();
				$noresult.show();
			}
		}
		, displayWriter: function(n){
			var $layer = this.$getLayer();
			var thisClass = this;
			var $obj = $layer.find("tbody tr").eq(n);
			
			$obj.find("td:eq(2) img").attr("src", _gf.filePath2Url(this.listData[n]["작성자"]["이미지"])).hover(function(){
				_gf.showProfileLayer($(this), thisClass.listData[n]["작성자"], "left", 0, $(this).height());
			}, function(){
				_gf.closeProfileLayer();
			});
			$obj.find("td:eq(2) span.nickname").html(this.listData[n]["작성자"]["닉네임"]).hover(function(){
				_gf.showProfileLayer($(this), thisClass.listData[n]["작성자"], "left", 0, $(this).height());
			}, function(){
				_gf.closeProfileLayer();
			});;
		}
		, spinStart: function(){
			var $layer = this.$getLayer();
			var $noresult = this._HTMLDom["$noresult"];
			
			$layer.hide();
			$noresult.hide();

			if($layer.next("div#tmpSpin").length == 0){
				$layer.after("<div id='tmpSpin' style='position:relative; width:670px; height:100px;' />");
			}
			$layer.next("div#tmpSpin").show().spin();
		}
		, spinEnd: function(){
			var $layer = this.$getLayer();
			
			$layer.next("div#tmpSpin").spin(false).hide();
			$layer.show();
		}
	}
	
	function clsComm()
	{
		this.bookingRequest = null;
		this.bookingList = null;
		this.bookingPageData = null;
		// 공지
		this.noticeInfo = null;
		
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){
			this.bookingList = [
				{
					"키": null
					, "번호": null
					, "제목": null
					, "댓글수": null
					, "작성자": {
						"아이디": null
						, "닉네임": null
						, "이미지": null
					}
					, "날짜": null
					, "조회수": null
				}
			];
			
			this.bookingRequest = {
				"검색종류": null
				, "검색어": null
				, "페이지": null
				, "내꺼": null
			}
			
			this.noticeInfo = {
				"공지키": null
				, "제목": null
			}
		}
		, setBookingRequest: function(key, val){
			this.bookingRequest[key] = val;
		}
		, getBookingRequest: function(){
			return this.bookingRequest;
		}
		, getBookingList: function(){
			var thisClass = this;
			
			var szTitle = "";
			var szContent = "";
			var szNick = "";
			
			switch(this.bookingRequest["검색종류"]+""){
				case "1":
					szContent = this.bookingRequest["검색어"];
					szTitle = this.bookingRequest["검색어"];
					break;
				case "0":
					szContent = this.bookingRequest["검색어"];
					szTitle = this.bookingRequest["검색어"];
				case "2":
					szNick = this.bookingRequest["검색어"];
					break;
			}
			
			// ajax
			var serviceName = (this.bookingRequest["내꺼"]) ? "getBookingBoardMyList":"getBookingBoardList";
			var curPage = this.bookingRequest["페이지"];
			
			document.objGlobal.ajax({
				"sid": "BB001",
				"servicename": serviceName,
				"listcount": 10,
				"currpageno": curPage
			}, {
				"title": szTitle
				, "content": szContent
				, "reg_nickname": szNick
			}, function(ret){
				if(ret["msp"]["contents"]["serviceResult"] == "00000"){
					thisClass.bookingPageData = {
						"전체수": ret["msp"]["contents"]["@totalcount"]
					}
					
					thisClass.bookingList = [];
					var no = ret["msp"]["contents"]["@totalcount"] - (curPage-1)*10;
					
					var items = ret["msp"]["contents"]["items"];
					if(items){
						if(!items.length){
							items = new Array(items);
						}
						
						for(var i=0;i<items.length;i++){
							var obj = items[i];
							obj["reg__date"] += "";
							
							thisClass.bookingList.push({
								"키": obj["board__seq"]
								, "번호": no-i
								, "제목": obj["title"]
								, "댓글수": obj["cr__cnt"]
								, "작성자": {
									"아이디": obj["reg__id"]
									, "닉네임": obj["reg__nickname"]
									, "이미지": obj["user__image"]
								}
								, "날짜": obj["reg__date"].substr(0,4) + "-" + obj["reg__date"].substr(4, 2) + "-" + obj["reg__date"].substr(6,2)
								, "조회수": obj["hit"]
								, "내꺼": obj["my__article__yn"]
							});
						}
					}
				}else{
					thisClass.bookingList = {
						"결과코드": ret["msp"]["contents"]["serviceResult"]
						, "메시지": document.objGlobal.getResultMsg(ret)
					}
				}
				
				document.objControl.finishBookingList();
			});
		}
		, getBookingData: function(){
			return this.bookingList;
		}
		, getBookingPageData: function(){
			return this.bookingPageData;
		}
		, getNoticeInfo: function(){
			var thisClass = this;
			
			//ajax
			var serviceName = "getBookingBoardList";
			
			document.objGlobal.ajax({
				"sid": "BB001",
				"servicename": serviceName,
				"listcount": 1,
				"currpageno": 1
			}, {
				"title": ""
				, "content": ""
				, "reg_nickname": ""
				, "notice_yn": "Y"
			}, function(ret){
				if(ret["msp"]["contents"]["serviceResult"] == "00000"){
					thisClass.noticeInfo = {};
					
					if(ret["msp"]["contents"]["items"]){
						var obj = ret["msp"]["contents"]["items"];
						
						thisClass.noticeInfo = {
							"공지키": obj["board__seq"]
							, "제목": obj["title"]
						}
					}
				}else{
					thisClass.bookingList = {
						"결과코드": ret["msp"]["contents"]["serviceResult"]
						, "메시지": document.objGlobal.getResultMsg(ret)
					}
				}
				
				document.objControl.finishNoticeInfo();
			});
		}
		, getNoticeData: function(){
			return this.noticeInfo;
		}
	}
	
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		this.objBookinTitle = null;
		this.objNotice = null;
		this.objBookingList = null;
		this.objBookingPage = null;
		this.objSearchType = null;
		this.objSearchText = null;
		
		this._permitStart = null;
		
		this.q_my = null;
		this.q_searchType = null;
		this.q_searchText = null;
		this.q_page = null;
	}
	
	clsControl.prototype = {
		_init: function(){
			this._preload();
			
			this.objComm = new clsComm();
			this.objBookingTitle = new clsBookingTitle();
			this.objNotice = new clsNotice();
			this.objBookingList = new clsBookingList();
			this.objBookingPage = new document.objGlobal.clsPaging($("#idBookingListPage"), 10, 10);
			this.objSearchType = new clsSearchType();
			this.objSearchText = new clsSearchText();
			
			this._beforeStart();
			this._bind();
		}
		, _preload: function(){
			_gf.spinStart();
		}
		, _beforeStart: function(){
			var thisClass = this;
			this._permitStart = {
				
			}
			
			_util.executeThread(function(){
				for(var key in thisClass._permitStart){
					if(!thisClass._permitStart[key]) return false;
				}
				
				return (thisClass.objBookingPage.getLoaded());
			}, function(){
				_gf.spinEnd();
				thisClass._start();
			});
		}
		, _bind: function(){
			var thisClass = this;

			// 전체게시글, 내가쓴글
			this.objBookingTitle.$getsBtnTab().click(function(){
				var idx = thisClass.objBookingTitle.$getsBtnTab().index($(this));
				
				if(idx == 1 && !_util.getCookie("member_id")){
					if(!confirm(_LOGIN_TEXT)){
						return;
					}
					_gf.goLogin();
					return;
				}
				
				document.location.href = document.location.pathname + ((idx) ? "?q_my=Y":"");
			});
			
			this.objSearchType.$getLayer().on("click", "p, li", function(){
				var tName = this.tagName.toUpperCase();
				
				switch(tName){
					case "P":
						thisClass.objSearchType.toggle();
						break;
					case "LI":
						var n = thisClass.objSearchType.$getLayer().find("li").index($(this));
						
						thisClass.objSearchType.setIdx(n);
						break;
				}
			});
			
			// 페이지이동
			$(this.objBookingPage).bind("evtPageClick", function(){
				var thisPage = this.getPage();
				
				thisClass.objComm.setBookingRequest("페이지", thisPage);
				thisClass.objBookingList.spinStart();
				thisClass.objComm.getBookingList();
			});
			
			// 검색
			$("article.golf_board_search :image").click(function(){
				if(!thisClass.objSearchText.isValid()){
					alert(thisClass.objSearchText.getError());
					thisClass.objSearchText.focus();
					return;
				}
				
				thisClass.objBookingPage.setPage(1);
				thisClass.fnBookingList();
			});
			this.objSearchText.$getObj().keydown(function(event){
				if(event.keyCode == 13){
					thisClass.objBookingPage.setPage(1);
					thisClass.fnBookingList();
				}
			});
			
			
			// 글쓰기
			$("div#container section#main_content div.golf_board a").has("img[alt=글쓰기]").click(function(){
				thisClass.goWritePage();
			});
		}
		, _start: function(){
			this.q_my = _util.getParam("q_my");
			this.q_searchType = _util.getParam("q_searchType");
			this.q_searchText = _util.getParam("q_searchText");
			this.q_page = _util.getParam("q_page");
			
			if(this.q_my == "Y" && !_util.getCookie("member_id")){
				if(!confirm(_LOGIN_TEXT)){
					history.back();
					return;
				}
				_gf.goLogin();
				return;
			}
			
			// 공지사항
			this.objComm.getNoticeInfo();
			
			// 전체게시글로 default 설정
			this.objBookingTitle.setIdx((this.q_my == "Y") ? 1:0);
			if(this.q_my == "Y") this.objComm.setBookingRequest("내꺼", true);
			
			if(this.q_searchType){
				this.objSearchType.setValue(this.q_searchType);
			}
			
			if(this.q_searchText){
				this.objSearchText.setValue(this.q_searchText);
			}
			
			if(this.q_page){
				this.objBookingPage.setPage(this.q_page);
			}else{
				this.objBookingPage.setPage(1);
			}
			
			this.objBookingList.spinStart();
			this.objComm.setBookingRequest("페이지", this.objBookingPage.getPage());
			this.fnBookingList();
		}
		// 리스트완료
		, finishBookingList: function(){
			var thisData = this.objComm.getBookingData();
			var pageData = this.objComm.getBookingPageData();
			var thisClass = this;
			
			this.objBookingList.spinEnd();
			
			if(thisData["메시지"]){
				alert(thisData["메시지"]);
				return;
			}
			
			this.objBookingList.setList(thisData);
			
			// 페이지 부에 전체 수설정 
			this.objBookingPage.setTotalCount(pageData["전체수"]);
			this.objBookingPage.display();
			// 작성자 정보
			for(var i=0;i<thisData.length;i++){
				_gf.getMemberInfo({
					"아이디": thisData[i]["작성자"]["아이디"]
					, "키": thisData[i]["키"]
					, "콜백": function(ret, info, arg){
						thisClass.objBookingList.setWriter(arg["키"], info);
					}
				});
			}
		}
		// 공지사항 완료
		, finishNoticeInfo: function(){
			var thisData = this.objComm.getNoticeData();
			
			this.objNotice.setInfo(thisData);
		}
		// 부킹리스트 받아오기
		, fnBookingList: function(){
			this.objComm.setBookingRequest("검색종류", this.objSearchType.getValue());
			this.objComm.setBookingRequest("검색어", this.objSearchText.getValue());
			this.objBookingList.spinStart();
			this.objComm.getBookingList();
		}
		, getParams: function(){
			var r = this.objComm.getBookingRequest();
			
			return {
				"q_my": this.q_my
				, "q_searchType": _util.nvl(r["검색종류"])
				, "q_searchText": _util.nvl(r["검색어"])
				, "q_page": _util.nvl(r["페이지"])
			}
		}
		// 보기 페이지 이동
		, goViewPage: function(q_seq){
			var r = this.getParams();
			
			r["q_seq"] = q_seq;
			
			document.location.href = "booking_view.html" + _util.object2paramString(r);
		}
		// 글쓰기 페이지
		, goWritePage: function(){
			if(!_util.getCookie("member_id")){
				if(!confirm(_LOGIN_TEXT)){
					return;
				}
				_gf.goLogin();
				return;
			}
			
			var szLink = "booking_write.html" + _util.object2paramString(this.getParams());
			
			document.location.href = szLink;
		}
	}
	
	document.objControl = new clsControl();
	document.objControl._init();
});